<?php
namespace app\admin\controller;

use think\Db;
use think\Response;
use think\Config;
use app\admin\controller\Base;
use app\admin\controller\Logsystem;
use app\admin\model\Student as StudentM;
use app\admin\model\Excelexport;
use app\admin\model\Excelexportadd;
use app\admin\model\Admin;
use think\exception\HttpResponseException;


class Student extends Base
{
    //前置操作
    protected $beforeActionList = [
        'myConfigs'         => ['except' => ' excelexport, allocation, swapResource'],
    ];

    //自定义公共配置参数
    protected function myConfigs()
    {
        $user = $this->user_info();
        $status_config        = Config::get('resstatus_config');      //资源状态 文本 颜色
        $education_select     = Config::get('education_select');      //文化程度select选项
        $contract_rate_select = Config::get('contract_rate_select');  //签约率
        $zx_course_select     = Config::get('zx_course_select');      //咨询课程 select选项
        
        //是否是市场部登录
        if(in_array($user['roles_id'],array(12,13,14))){
            $is_shichang = true;
        }else {
            $is_shichang = false;
        }

        $receptionist = db("admin")->where(array('roles_id' => ['in','13, 14'], 'poststatus' => 1, 'status'=>1))->select(); 
        $consultant = db("admin")->where(array('roles_id' => 6, 'poststatus' => 1, 'status'=>1))->select(); 

        $this->assign([
            'ra'                   => $user['ra'],//当前用户的资源管理权限
            'is_shichang'          => $is_shichang, //是否是市场部登录
            "status_config"        => $status_config, //状态配置数组
            'education_select'     => $education_select,//学历选项
            "zx_course_select"     => $zx_course_select, //签约率选项
            "contract_rate_select" => $contract_rate_select,  //签约率选项
            'roles_id'             => $user['roles_id'], //当前用户角色
            'receptionist'         => $receptionist,//接待员
            'consultant'         => $consultant//咨询顾问
        ]);
    }


    //根据当前用户角色设置查询条件
    private function setWhereForThisUser () {
        $user = $this->user_info();
        $roles_id = $user['roles_id'];
        switch ($roles_id) {
            case 6: //咨询顾问
                $where = array("consultant" => $user['id']);
                break;
            case 14: //接待员
                $where = array("receptionist" => $user['id']);
                break;
            default:
                $where = array();
                break;
        }
        return $where;
    }

    //设置筛选条件
    private function setScreeningConditions () {
        $key = input('get.key');
        $field = input('get.field');
        $key = trim($key); //搜索关键字
        $query  = array(); //分页的query选项
        $searchWhere = array(); //筛选条件
        $order = '';
        //是否按时间区间查询
        if (input('?get.start') && input('?get.end')) {
            $time_field = input('time_field');
            if($time_field == 'returnvisit_time' || $time_field == 'status_time'){
                $start_time = input('get.start');
                $end_time = input('get.end');
            } else {
                $start_time = strtotime(input('get.start'));
                $end_time = strtotime(input('get.end'))+3600*24;
            }
            
            if(!empty($start_time) && !empty($end_time)) {
                $searchWhere["s.".$time_field] = ['between',"$start_time, $end_time"];
                $query['start'] = input('get.start');
                $query['end'] = input('get.end');
                $query['time_field'] = $time_field;
            }
            if($time_field == 'status_time'){
                $order = "field(sstatus,1) desc,";
            }
        }

       

        //组织筛选条件
        if (!empty($key)){
            $searchWhere["$field"] = ['like', "%" . $key . "%"];
            $query['field'] = $field;
            $query['key'] = $key;
        }

        $order = new \think\db\Expression("$order sid asc"); //自定义排序规则
        return array(
            'searchWhere'=> $searchWhere,
            'query'=>$query,
            'order'=> $order
        );
    }


    //根据不同状态获取数据
    private function getDataForThisStatus ($status=-1) {
        $StudentM = new StudentM;
        $ScreeningConditions = $this->setScreeningConditions();
        $where = $ScreeningConditions['searchWhere'];
        $query = $ScreeningConditions['query'];
        $order = $ScreeningConditions['order'];

        if($status != -1) {
            $where['sstatus'] = $status;
        } 

        //是否按时间区间查询
        $res = $StudentM
            ->where($where)
            ->where($this->setWhereForThisUser())
            ->alias('s')
            ->order($order)
            ->join('admin a2', 's.receptionist = a2.id', 'left')
            ->field('s.*,a2.username as receptionist')
            ->paginate(30 , false, ['query' => $query]);
        return [
            "res" => $res, //展示的数据
        ];
    }

    //根据不同状态和咨询师获取数据
    private function getDataForThisStatusAndConsultant ($status = -1) {
        $StudentM = new StudentM;
        $ScreeningConditions = $this->setScreeningConditions();
        $where = $ScreeningConditions['searchWhere'];
        $query = $ScreeningConditions['query'];
        $order = $ScreeningConditions['order'];

        if($status != -1) {
            $where['sstatus'] = $status;
        } 

        $res = $StudentM
            ->alias('s')
            ->where($where)
            ->where($this->setWhereForThisUser())
            ->order($order)
            ->join('admin a', 's.consultant = a.id')
            ->join('admin a2', 's.receptionist = a2.id')
            ->field('s.*,a.username as zxsname,a2.username as receptionist')
            ->paginate(10, false, ['query' => $query]);

        return [
            "res" => $res,
        ];
    }

    //展示新资源
    public  function index () {
        //查询咨询师
        $zxs = db("admin")->where(array('roles_id' => 6, 'poststatus' => 1, 'status'=>1))->select(); 
        $data = $this->getDataForThisStatus(3);
        $data['zxs'] = $zxs;
        $this->assign($data);
        return  $this->fetch();
    }

    //展示旧资源
    public  function indexoldrexi()
    {
        //查询咨询师
        $zxs = db("admin")->where(array('roles_id' => 6, 'poststatus' => 1, 'status'=>1))->select(); 

        $data = $this->getDataForThisStatusAndConsultant(4);
        $data['zxs'] = $zxs;
        $this->assign($data);
        return  $this->fetch();
    }

    //展示长期资源
    public  function longres()
    {
        $data = $this->getDataForThisStatusAndConsultant(5);
        $this->assign($data);
        return  $this->fetch();
    }

    //数据总表
    public function allres(){
        $data = $this->getDataForThisStatusAndConsultant();
        $this->assign($data);
        return  $this->fetch();
    }

    // 沉默客户
    public  function chenmo()
    {
        $this->assign($this->getDataForThisStatusAndConsultant(0));
        return $this->fetch();
    }

    // 签约客户
    public  function qianyue()
    {
        $this->assign($this->getDataForThisStatusAndConsultant(1));
        return $this->fetch();
    }

    // 跟进客户
    public  function genjin()
    {
        $this->assign($this->getDataForThisStatusAndConsultant(2));
        return $this->fetch();
    }


    /**
     * Myreception  当前接待员所接待的数据
     * @author wzk <email@email.com>
     */
    public function myreception()
    {
        $user = $this->user_info();
        //组织查询条件
        $key = input('get.key');
        $searchStatus = input('get.searchStatus');
        $key = trim($key); //搜索关键字
        $search = [];
        if ( !empty($key) || $searchStatus>=0 ) $search = ["sname|stel|zxr_tel|semai|zxr_name" => ['like', "%" . $key . "%"], 'sstatus'=>"'$searchStatus'"];
      
        $res = db("student")->where(array( "receptionist" => $user['id']))->where($search)->order('sid', 'DESC')
            ->alias('s')
            ->join('admin a', 's.consultant = a.id','left')
            ->join('admin a2', 's.receptionist = a2.id', 'left')
            ->field('s.*,a.username as zxsname,a2.username as receptionist')
            ->paginate(10);
           
        $this->assign([
            "res" => $res,
            "oldkey" => $key,  //搜索关键字
        ]);
        return $this->fetch();
    }


    //添加 start
    //学生信息添加视图
    public  function information()
    {
        $receptionist = Db::name('admin')->where('roles_id', 'in', [13, 14])->select();
        $this->assign(array(
            'receptionist' => $receptionist,
        ));
        return  view();
    }

    // 提交学生信息添加
    public function add()
    {
        $data = input("post.");
        if( empty( $data['sname'] ) ){ 
            $this->error('请填写学生姓名');
        }

        if ($data['zxr_tel'] != '') {
            $is_phone = regexCheck('phone', $data['zxr_tel']);
            if ($is_phone) {

                $repeat_phone = StudentM:: //查询是否有重复数据
                where("zxr_tel", $data['zxr_tel'])
                ->count();

                if ($repeat_phone > 0) $this->error("有重复资源", '', $repeat_phone);

            } else {

                $this->error('手机号码格式错误');

            }
        } else if ($data['wechatqq'] != '') {

            $repeat_wechatqq = StudentM:: //查询是否有重复数据
                where("wechatqq", $data['wechatqq'])
                ->count();

            if ($repeat_wechatqq > 0) $this->error("有重复资源", '', $repeat_wechatqq);

        } else {

            $this->error('手机号码或微信至少填写一项');

        }

        //手机号格式正确并且姓名不为空则添加数据
      

            $student = new StudentM();
            $res = $student->save($data); //添加数据
            if ($res) {
                echo $this->success('添加成功');
            } else {
                echo $this->error('添加失败');
            }
        
    }
    //添加 end


    //修改更新数据 start
    // 修改学生信息 视图
    public function update()
    {
        $data = input("get.id");
        $student = new StudentM();
        $res = $student->where('sid', $data)->find();

        $this->assign([
            'data' => $res,
        ]);
        return  $this->fetch();
    }

    // 执行修改
    public  function sav()
    {
        $e = input("post.");

        $student = new StudentM();
        $student_data = Db::name('student')->where('sid', $e['sid'])->find();
        $resid = input('post.sid');
        $logtext = input('post.logtext');
        unset($e['logtext']);
        $user = $this->user_info();

        if(isset($e['zxr_tel'])){
            if( !($e['zxr_tel'] == '' || empty($e['zxr_tel'])) ){
                $searchdata = StudentM:: //查询咨询人手机是否有重复数据
                    where(array(
                        "zxr_tel"=>$e['zxr_tel'],
                        'sid'=>['neq', $e['sid']]
                        ))
                    ->find();
                    if ($searchdata) {
                        $this->error("咨询人手机号重复", '', $searchdata);
                    }
            }
        }
        
        if(isset($e['wechatqq'])){
            if( !($e['wechatqq'] == '' || empty($e['wechatqq'])) ){
                $wechatqqReRes = StudentM:: //查询微信是否有重复数据
                    where(array(
                        'wechatqq'=>$e['wechatqq'],
                        'sid'=>['neq', $e['sid']]
                    ))
                    ->find();
                if($wechatqqReRes) {
                    $this->error("微信号重复", '', $wechatqqReRes);
                }
            }
        }
        if( !($e['wechatqq'] == '' || empty($e['wechatqq'])) ){
            $wechatqqReRes = StudentM:: //查询微信是否有重复数据
                where(array(
                    'wechatqq'=>$e['wechatqq'],
                    'sid'=>['neq', $e['sid']]
                ))
                ->find();
            if($wechatqqReRes) {
                $this->error("微信号重复", '', $wechatqqReRes);
            }
        }
       
        //比对状态是否修改 
        if (isset($e['sstatus']) && $student_data['sstatus'] != $e['sstatus']) {
            //状态定义时间
            $e['status_time'] = date('Y-m-d H:i:s', time());
        }
        
        $res = $student->save($e, ['sid' => $e['sid']]);
        if ($res) {//更新数据成功
            if(!empty(trim($logtext))){  //如果日志内容不为空 添加咨询日志
                $re = db('zxlog')->insert([
                    'res_id'=>$resid,
                    'content'=>$logtext,
                    'operator'=> $user['id'],
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
            }
            $this->success('修改成功');
        } else {
            $this->error("修改失败");
        }
    }
    //修改更新数据 end

    //删除学生信息
    public function delete()
    {
        $da = input("post.id");
        $idArr = json_decode($da, true);

        $res = db("student")->where("sid", 'in', $idArr)->delete();
        if ($res) {
            echo "1";
        } else {
            echo "0";
        }
    }


    //添加数据 手机号查重 返回json
    public function searchRes($type, $value)
    {
        if ( !empty(trim($value)) ) {
            $stu = new StudentM;
            $res = StudentM::where("$type", $value)
                ->alias('s')
                ->join('admin a', 's.consultant = a.id', 'left')
                ->join('admin a2', 's.receptionist = a2.id', 'left')
                ->field('s.*, a.username as consultant,a2.username as receptionist')
                ->select();
            if ($res) {
                return $res;
            } else {
                return false;
            }
        }

    }

    // excel 导入新资源
    public function exceladd()
    {
        $data = input('post.data');  //获取post.data
        $is_data = input('?post.data');  //post.data是否存在
        $data = json_decode($data, true);  //json字符串转数组
        $receptionist = input('post.receptionist');  //接待员id

        //将所有手机号和微信号组装成数组
        $zxr_tel_arr = array();
        $wechat_arr = array();
        foreach ($data as $k => $v) {
            if( !empty( $v['zxr_tel']  )){
                $zxr_tel_arr[] = $v['zxr_tel'];
            }
            
            if( !empty( $v['wechatqq'] ) ){
                $wechat_arr[] = $v['wechatqq'];
            }
            
        }
        //按手机号查询 得到重复的数据
        if(!empty($zxr_tel_arr))
        $zxr_tel_arr = StudentM::where('zxr_tel', 'in', $zxr_tel_arr)->column('zxr_tel');
        if(!empty($wechat_arr))
        $wechat_arr = StudentM::where('wechatqq', 'in', $wechat_arr)->column('wechatqq');

        //数据去重 将重复数据剔除出$data
        $repeatArr = array(); //重复数据
        $re = assoc_unique([$data, $repeatArr], 'zxr_tel', $zxr_tel_arr);
        $re = assoc_unique($re, 'wechatqq', $wechat_arr);
        list($data, $repeatArr) = $re;

        //所有咨询顾问
        $consultant_list = Admin::where('roles_id',6)->column('username,id');
        $receptionist_list = Admin::where('roles_id','in','13,14')->column('username,id');
      
        // 验证手机号格式
        foreach ($data as $k => $v) {
            $is_match = regexCheck('phone', $v['zxr_tel']);
            if( $v['zxr_tel'] != '' && !$is_match){
                    $v['msg'] = '手机号码格式错误';
                    $repeatArr[] = $v;
                    unset($data[$k]);
                    continue;
            } else if ($v['wechatqq'] == '' && $v['zxr_tel'] == '') {
                    $v['msg'] = '数据不完整';
                    $repeatArr[] = $v;
                    unset($data[$k]);
                    continue;
            }

            $status_id = getStatusId($v['sstatus']);
            if( $status_id != -1 ){
                if(is_array($status_id)){
                    $data[$k]['sstatus'] = $status_id['sstatus'];
                    $data[$k]['contract_rate'] = $status_id['contract_rate'];
                } else {
                    $data[$k]['sstatus'] = $status_id;
                }
            } else {
                $v['msg'] = '未知状态';
                $repeatArr[] = $v;
                unset($data[$k]);
                continue;
            }

            $consultant_id = getConsultantId($v['consultant'],$consultant_list);
            $receptionist_id = getReceptionistId($v['receptionist'],$receptionist_list);

            if( $consultant_id != -1 ){
                $data[$k]['consultant'] = $consultant_id;
            } else {
                $v['msg'] = '未知顾问';
                $repeatArr[] = $v;
                unset($data[$k]);
                continue;
            }

            if( $receptionist_id != -1 ){
                $data[$k]['receptionist'] = $receptionist_id;
            } else {
                $v['msg'] = '未知接待员';
                $repeatArr[] = $v;
                unset($data[$k]);
                continue;
            }

            if($receptionist != -1){
                $data[$k]['receptionist'] = $receptionist;  //将接待员id添加到数组中
            }
            $data[$k]['create_time'] = strtotime($data[$k]['create_time']);  //转换时间戳
        }

        if ($is_data) {
            $redata['insert_num'] = count($data); // 符合条件的数据 条数
            $redata['noinsert_num'] = count($repeatArr); // 不符合条件的数据 条数

            if ($redata['insert_num'] > 0) { //是否有数据要被添加
                $student = new Excelexportadd();
                $insert_re = $student->saveAll($data);
                
                if (!$insert_re) {
                    $this->error('添加数据失败');
                } else {
                    // 将旧的咨询日志添加到旧的咨询日志表
                    $loadata = array();
                    foreach ($insert_re as $res) {
                        $loadata[]=[
                            'res_id' => $res['sid'],
                            'content' => $res['oldzxlog'],
                            'operator' => 1,
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                        $res->oldzxlog = '';
                        $res->save();
                    }
                    $re = db('zxlog')->insertAll($loadata);
                }
            }

            //导入成功 返回信息
            //因重复或手机号码格式错误 无法插入的数据
            $redata['repeatArr'] = $repeatArr;
            $this->success('添加成功', null, $redata);
        } else {
            print_r('非法操作，未发现数据');
        }
    }


    //数据导出页面
    public function excelexportpage()
    {
        return $this->fetch();
    }


    //数据导出
    public function excelexport()
    {
        $startime = strtotime(input('post.startime'));
        $endtime = strtotime(input('post.endtime'));
        $sstatus = input('post.sstatus');
       
        if($endtime == '' || $startime ==''){
            $where = array();
        }else{
            $where  = array('s.create_time'=>['between time',[$startime, $endtime]]);
        }

        if($sstatus != -1){
            $where['s.sstatus'] = $sstatus;
        }
        
        
        $Excelexport = new Excelexport();
      
        $data = $Excelexport  //查询要导出的数据
            ->alias('s')
            ->join('admin a', 's.consultant = a.id', 'left')
            ->join('admin a2', 's.receptionist = a2.id', 'left')
            ->field('s.*, a.username as consultant,a2.username as receptionist')
            ->where($where)
            ->select();
     
        $result = [ //按Excel插件要求 阻止返回数据
            'code'  => 0,
            'msg'   => "", 
            "count" => count($data),//数据数目
            'data'  => $data,  //实际要用的数据
        ];

        $response = Response::create($result, 'json')->header([]);

        throw new HttpResponseException($response);
    }



    /**
     * allocation  资源分发
     * @return void
     */
    public function allocation()
    {
        $id = json_decode(input('post.resid'));  //资源id
        $zxs_id = json_decode(input('post.zxsid'));  //咨询师id

        //判断用什么方式分发
        if ($id == 'all') {  //接收前端传过来的资源id 如果是 all 则代表自动分配所有
            if (is_array($zxs_id) && !empty($zxs_id)) {  //如果用户 指定了咨询师
                $zxs = db('admin')->where('id', 'in', $zxs_id)->where(['poststatus' => 1, 'roles_id' => 6])->select();  //咨询师
            } else {  //没有指定咨询师 查询所有正常状态的咨询师
                $zxs = db('admin')->where(['poststatus' => 1, 'roles_id' => 6])->select();  //咨询师
            }

            $res = Db::name('student')->where('sstatus', 'in', [3, 4])      //资源
                ->where(['drop_time' => [['<=', time() - 3600 * 24], ['eq', 0], 'or']])
                ->select();

        } else if (is_array($id) && !empty($id)) {  //如果选定了资源id
            //用户指定了 要分配的资源
            $res = Db::name('student')->where('sid', 'in', $id)      //资源
                ->where('sstatus', 'in', [3, 4])
                ->where(['drop_time' => [['<=', time() - 3600 * 24], ['eq', 0], 'or']])
                ->select();

            if (is_array($zxs_id) && !empty($zxs_id)) {  //如果用户 指定了咨询师
                $zxs = db('admin')->where('id', 'in', $zxs_id)->where(['poststatus' => 1, 'roles_id' => 6])->select();  //咨询师
            } else {  //没有指定咨询师 查询所有正常状态的咨询师
                $zxs = db('admin')->where(['poststatus' => 1, 'roles_id' => 6])->select();  //咨询师
            }

        } else {
            $this->error('数据异常');
        }


        if (count($res) <= 0) $this->error('没有可分配资源');
        if (count($zxs) <= 0) $this->error('当前没有可以接受资源咨询师');


        $update_arr = array();  //保存最终要更新的数据
        $transfer = array();  //中转数组

        //开始分发
        for ($i = 0; $i < count($res); $i++) {  //遍历资源
            $zx_history = array_filter(explode(',', $res[$i]['zx_history'])); //历史咨询师

            if (count($zxs) == 0) {  //当所有咨询师被分过一遍, 则重新赋值 进行下一轮
                $zxs = $transfer;
                $transfer = array();
            }

            foreach ($zxs as $k => $v) {  //为资源匹配咨询师 条件 不能是曾经分配过的 
                if (!in_array($v['id'], $zx_history) || count($zxs_id) == 1) {  //判断当前咨询师是否曾经拥有过此资源
                    // $zx_history[] = $v['id']; //将咨询师id 加入到资源的历史咨询师列表
                    $update_arr[] = array('sid' => $res[$i]['sid'], 'sstatus' => 2, 'zx_history' => $res[$i]['zx_history'], 'consultant' => $v['id'], 'zxlast_time' => time());
                    $transfer[] = $v;
                    unset($zxs[$k]);
                    break;
                }

                if ($v == end($zxs)) { //判断是否是本轮最后一项 一般执行不到这一步 就在
                    // 如果执行到这里 说明 当前资源在本轮里找不到可以分配的资源 , 那么就会执行交换函数
                    $return = $this->swapResource($update_arr, $zxs, $res[$i]);
                    if (!empty($return)) {

                        $update_arr = $return['update_arr'];
                        $zxs = $return['zxs'];
                        $transfer[] = $return['transfer'];
                    }
                }
            }
        }


        //更新每条资源的咨询历史
        foreach ($update_arr as $k => $v) { 
            $zx_history = explode(',', $v['zx_history']);
            $zx_history[] = $v['consultant'];
            $update_arr[$k]['zx_history'] = trim(implode(',', $zx_history), ',');
        }

        //跟新数据
        $student = new StudentM();
        $re = $student->saveAll($update_arr);

        if ($re) {  //判断分发结果
            $this->success('分发完成');
        } else {
            $this->error('分发失败,数据异常');
        }


    }


    /**
     * swapResource  资源交换 [当碰到资源在本轮中找不到可以分配的咨询师时, 可以找与其他已分配的资源交换]
     *
     * @return void
     */
    public function swapResource($update_arr, $zxs, $value)
    {
        foreach ($update_arr as $uk => $uv) {
            $value_history = array_filter(explode(',', $value['zx_history']));  //需要交换的资源的 历史咨询师

            if (!in_array($uv['consultant'], $value_history)) {  //需要交换的资源 是否能分配给 当前循环的资源的 咨询师 
                $zx_history = array_filter(explode(',', $uv['zx_history'])); //历史咨询师

                foreach ($zxs as $zk => $zv) {
                    if (!in_array($zv['id'], $zx_history)) {
                        $update_arr[] = array('sid' => $value['sid'], 'sstatus' => 2, 'zx_history' => $value['zx_history'], 'consultant' => $uv['consultant']);
                        $update_arr[$uk]['consultant'] = $zv['id'];
                        $transfer = $zv;
                        unset($zxs[$zk]);
                        return array('update_arr' => $update_arr, 'zxs' => $zxs, 'transfer' => $transfer); //返回交换过的数据
                    }
                }
            }
        }
    }




}
